package com.atguigu.bigdata.gmall.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.bigdata.gmall.realtime.app.BaseAppV1;
import com.atguigu.bigdata.gmall.realtime.bean.TrafficChCount;
import com.atguigu.bigdata.gmall.realtime.common.Constant;
import com.atguigu.bigdata.gmall.realtime.util.AtguiguUtil;
import com.atguigu.bigdata.gmall.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;


public class Dws_01_DwsTrafficChCount extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_01_DwsTrafficChCount().init(
                3001,
                1,
                "Dws_01_DwsTrafficChCount",
                Constant.TOPIC_DWD_TRAFFIC_PAGE
        );
    }
    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        //1.封装到一个pojo中
        SingleOutputStreamOperator<TrafficChCount> beanStream = parseToPojo(stream);
        //2.开窗聚合
        SingleOutputStreamOperator<TrafficChCount> resultStream = windowAddAgg(beanStream);
        resultStream.print();
        //3.写入到clickhouse中
        writeToClickHouse(resultStream);
    }

    private void writeToClickHouse(SingleOutputStreamOperator<TrafficChCount> resultStream) {
        resultStream
                .addSink(FlinkSinkUtil.getClickHouseSink("dws_traffic_Ch_count ",TrafficChCount.class));
    }

    private SingleOutputStreamOperator<TrafficChCount> windowAddAgg(SingleOutputStreamOperator<TrafficChCount> beanStream) {
        return beanStream
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<TrafficChCount>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((bean,ts) -> bean.getTs())
                                .withIdleness(Duration.ofMillis(1))
                )
                .keyBy(bean -> bean.getSc() )
                .window(TumblingEventTimeWindows.of(Time.seconds(1)))
                .reduce(
                        new ReduceFunction<TrafficChCount>() {
                            @Override
                            public TrafficChCount reduce(TrafficChCount bean1, //bean1是老数据   bean2是新来的数据
                                                         TrafficChCount bean2) throws Exception {
                                bean1.setPvCt(bean1.getPvCt() + bean2.getPvCt());  //页面浏览数
                                bean1.setSidCount(bean1.getSidCount() + bean2.getSidCount());  //会话总数
                                bean1.setUvCt(bean1.getUvCt() + bean2.getUvCt());  //独立访客数
                                bean1.setDurSum(bean1.getDurSum() + bean2.getDurSum());
//                                System.out.println("22222222");
                                return bean1;
                            }
                        },
                        // 泛型一: 表示输入. 前面的聚和 结果 的类型.
                        new ProcessWindowFunction<TrafficChCount, TrafficChCount, String, TimeWindow>() {
                            @Override
                            public void process(String key,  //key的值
                                                Context ctx,   //上下文对象
                                                Iterable<TrafficChCount> elements,   // 存储的当前这个窗口最终聚合结果: 这个集和有且仅有一个值
                                                Collector<TrafficChCount> out) throws Exception {

                                TrafficChCount bean = elements.iterator().next();
                                //System.out.println("11111111111111111111111");
                                //补充窗口开始和结束
                                bean.setStt(AtguiguUtil.toDatTime(ctx.window().getStart()));
                                //System.out.println("-------------------------" + bean.getStt());
                                bean.setEdt(AtguiguUtil.toDatTime(ctx.window().getEnd()));
                                if (bean.getSidCount() != 0) {
                                    //计算会话平均浏览页面
                                    bean.setAvgTrafficPage(bean.getPvCt() / bean.getSidCount());
                                    //会话平均停留时长
                                    bean.setAvgDuringTime(bean.getDurSum() / bean.getSidCount());

                                }
                                //表示这个结果的统计时间
                                bean.setTs(System.currentTimeMillis());

                                out.collect(bean);


                            }
                        }
                );

    }

    private SingleOutputStreamOperator<TrafficChCount> parseToPojo(DataStreamSource<String> stream) {
        return stream
                .map(JSON::parseObject)
                .keyBy(obj -> obj.getJSONObject("common").getString("mid"))
                .map(new RichMapFunction<JSONObject, TrafficChCount>() {
                    private ValueState<String> dateState;
                    @Override
                    public void open(Configuration parameters) throws Exception {
                        dateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("dateState",String.class));
                        System.out.println(dateState + "-----------------");
                    }

                    @Override
                    public TrafficChCount map(JSONObject obj) throws Exception {
                        JSONObject common = obj.getJSONObject("common");
                        JSONObject page = obj.getJSONObject("page");
                        String sc = common.getString("sc");
                        String vc = common.getString("vc");
                        String mid = common.getString("mid");
                        String sid = common.getString("sid");
                        String ar = common.getString("ar");
                        String isNew = common.getString("is_new");
                        Long ts = obj.getLong("ts");
                        //页面浏览数
                        Long pvCt = 1l;
                        Long durSum = page.getLong("during_time");

                        //会话总数
                        Long sidCount = 0l;
                      
                        String lastPageId = page.getString("last_page_id");
                        if (lastPageId == null || lastPageId.length() == 0) {
                            sidCount = 1l;
                        }

                        //独立访客数
                        Long uvCt = 0l;
                        //状态中存储年月日，如果来的数据的日期和状态不一样，就是当天的第一条 ucCt=1 更新状态
                        //否则就不是第一条
                        String date = dateState.value();
                        String today = AtguiguUtil.toDate(ts);
                        if (!today.equals(date)){
                            //更新状态
                            dateState.update(today);
                            uvCt = 1l;

                        }
                        return new TrafficChCount("","",vc,sc,ar,isNew,uvCt,pvCt,durSum,sidCount,0l,0l,ts);
                    }
                });
    }


    }

